package com.njcc.control;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.njcc.po.FileInfo;
import com.njcc.service.GetFilePages;
import com.njcc.service.impl.CountPriceServiceImpl;
import com.njcc.util.DBCon;

import net.sf.json.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * 获得客户端上传的文件，保存在指定位置，并且分析文件信息，将信息返回给客户端
 */
@WebServlet("/GetFileServlet")
public class GetFileServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Logger logger = LogManager.getLogger(GetFileServlet.class);
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetFileServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//设置向客户端发送数据的json对象的编码格式
		response.setContentType("text/json;charset=utf-8");
		response.setCharacterEncoding("utf8");
		
		/**
		 * 拿到GetFileNameServlet存在application中的fileName
		 */
		ServletContext context = getServletContext();
		String name = (String) context.getAttribute("fileName");
		logger.info("GetFileServlet:"+name);
		
		/**
		 * 判断有没有获取到name，只有得到name后才能保存上传的文件
		 */
		if(name != null){
			
			InputStream is = request.getInputStream();
			FileOutputStream fos = new FileOutputStream(DBCon.file_Path+name);//上传的文件的存储位置
			byte[] b = new byte[1024];
			int len = 0;
			while((len = is.read(b)) != -1){
				fos.write(b, 0, len);
			}
			
			//System.out.println("GetFileServlet已经收到："+fos.toString());
			
			//关闭流
			fos.close();
			is.close();
			
			//分装JSON对象，将分析之后的文件信息返回给客户端
			FileInfo fileInfo = dealFile(name);
			getServletContext().setAttribute("fileInfo", fileInfo);//在application中保存fileInfo
			JSONObject result = JSONObject.fromObject(fileInfo);
			response.getWriter().write(result.toString());
			
            logger.info("fileInfo:"+result.toString());
		}else{
			/**
			 * 没有收到客户端提前上传的文件名，设置服务器状态为500
			 */
			response.setStatus(500);
		}
	}
	
	/**
	 * 分析接受到的文件，并返回fileInfo对象
	 * @param name	文件名
	 * @return fileInfo 
	 * @throws IOException
	 */
	public FileInfo dealFile(String name) throws IOException{
		
		FileInfo fileInfo = new FileInfo();
	
		String[] str = name.split("\\.");
		String kind = "."+str[1];	//获得文件的后缀名
		double cost = 0;
		int pages = 0;
		
		if(kind.equals(".doc")){
			kind = "word";
			cost = new CountPriceServiceImpl().getWordPrice(name);
			pages = new GetFilePages().getPages4DOC(name);
		}
		if(kind.equals(".docx")){
			kind = "word";
			cost = new CountPriceServiceImpl().getWordPrice(name);
			pages = new GetFilePages().getPages4DOCX(name);
		}
		if(kind.equals(".pdf")){
			kind = "PDF";
			cost = new CountPriceServiceImpl().getPDFPrice(name);
			pages = new GetFilePages().getPDFPages(name);
		}
		if(kind.contains(".jpg") || kind.contains(".png")){
			kind = "图片";
			cost = new CountPriceServiceImpl().getImgPrice(name);
			pages = 1;
		}
		
		//将文件信息分装到fileInfo对象
		fileInfo.setName(name);
		fileInfo.setPages(pages);
		fileInfo.setCost(cost);
		fileInfo.setKind(kind);

		return fileInfo;
		
	}

}
